import zipfile
import itertools
import time
import sys

def crack_zip(zip_file, charset, max_length):
    start_time = time.time()
    total_attempts = sum(len(charset) ** length for length in range(1, max_length + 1))
    attempted = 0
    
    zipf = zipfile.ZipFile(zip_file)
    print(f"开始破解 {zip_file}，共需尝试 {total_attempts} 种组合...")

    for length in range(1, max_length + 1):
        for attempt in itertools.product(charset, repeat=length):
            password = ''.join(attempt)
            attempted += 1
            
            # 动态显示进度（每秒更新一次）
            if attempted % 1000 == 0 or attempted == total_attempts:
                elapsed = time.time() - start_time
                speed = attempted / max(elapsed, 1e-9)  # 防止除以零
                remaining = (total_attempts - attempted) / max(speed, 1e-9)
                sys.stdout.write(
                    f"\r进度: {attempted}/{total_attempts} | "
                    f"当前尝试: {password.ljust(max_length)} | "
                    f"速度: {speed:.1f} 次/秒 | "
                    f"剩余时间: {remaining:.1f} 秒"
                )
                sys.stdout.flush()

            try:
                zipf.extractall(pwd=password.encode())
                print(f"\n\n密码找到：{password}")
                print(f"总耗时: {time.time() - start_time:.2f} 秒")
                return password
            except:
                continue

    print("\n\n未找到密码")
    return None

# 示例：尝试数字密码，最大长度 6
try:
    crack_zip("D:\\byd_softwares\\w2ksp4_en&instMsiW.zip", "0123456789", 6)
except KeyboardInterrupt:
    print("\n用户手动中断！")